package org.fing.edu.uy.esbadp.action.randomBalance;

import java.util.List;
import java.util.Random;
import java.util.logging.Level;

import org.fing.edu.uy.esbadp.assertion.AssertProperty;
import org.fing.edu.uy.esbadp.core.AdpFlowConstants;
import org.fing.edu.uy.esbadp.core.AdpFlowInterface;
import org.fing.edu.uy.esbadp.core.AdpFlowTree;
import org.fing.edu.uy.esbadp.core.entity.GenericTreeNode;
import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.jboss.internal.soa.esb.assertion.AssertArgument;
import org.jboss.soa.esb.actions.ActionProcessingException;
import org.jboss.soa.esb.actions.annotation.Process;
import org.jboss.soa.esb.message.Message;

public class RandomBalanceAction {
	
	private static java.util.logging.Logger logger = LoggerADP.getLogger(RandomBalanceAction.class.getSimpleName());
	
	public RandomBalanceAction() {
		
	}
	
	/**
	 * @param message
	 */
	@Process
	public Message process(Message message) throws ActionProcessingException {
		
		if(logger.isLoggable(LoggerADP.DEBUG_LEVEL)){
			logger.log(LoggerADP.DEBUG_LEVEL, "Process Action -> {0}", this.getClass().getName());
		}
		
		AssertArgument.isNotNull(message, "message");
		AssertProperty.isNotNull(message, AdpFlowConstants.PropertyFlowServices);

		try {
			// se obtiene tree de propiedades
			AdpFlowTree adpFlowTree = (AdpFlowTree) message.getProperties().getProperty(AdpFlowConstants.PropertyFlowServices);
			
			// voy a obtener la lista de hijos de el nodo.
			GenericTreeNode<AdpFlowInterface> treeNode = adpFlowTree.getCurrent();
			List<GenericTreeNode<AdpFlowInterface>> childrens = treeNode.getChildren();

			//selecciono randomicamente uno de los hijos
			int randomID = generateRandom(childrens.size());
			GenericTreeNode<AdpFlowInterface> nextCurrent = childrens.get(randomID);
			
			//seteo el proximo nodo al cual debo invocar
			adpFlowTree.setCurrent(nextCurrent);

		} catch (Exception ex) {
			logger.log(Level.SEVERE,"Exception in RandomBalanceAction when delivery Sync Message", ex);
		}
		return message;
	}

	private int generateRandom(int size) {
		Random r = new Random();
		int x = r.nextInt(size);
		return x;
	}

}
